Detailed explanation of optimized verification code mechanism in CI framework tutorial [verification code auxiliary function]

  • 2021-12-09 08:22:25
  • OfStack

This paper illustrates the optimized verification code mechanism of CI framework tutorial. Share it for your reference, as follows:

The verification code mechanism is implemented in the CI framework through an auxiliary function captcha ()-the verification code auxiliary function file contains a number of functions to help you create verification code pictures. .

So how do we use the captcha () helper function of CI to complete the verification code function? Next, I will first talk about how to use captcha () auxiliary function of CI to complete the verification code function, and then talk about how to specifically optimize the verification code mechanism of CI framework.

1. The use of CI framework verification code function

a) First we have to load the helper function

There are two ways to load helper function 1:

① Automatic loading

We can set up automatic loading in the file "application/config/autoload. php" under the root file directory.


//ci Frame Settings Autoload Helper Function 
//captcha Verification code copy function 
$autoload['helper'] = array('url','captcha');

Since the use of verification code in our project is very limited, it is not recommended to use this method automatically. We can load it where we use it.

② Load at the place where it is used

We still recommend this method, which consumes less resources and has a slightly higher efficiency of 1 point. Write a constructor in the controller where you use the verification code, and load the auxiliary function of the verification code in the constructor.


// Constructor 
public function __construct()
{
  // Remember in the constructor of the controller 1 Constructor that inherits the parent class controller first 
  parent::__construct();$this->load->helper('captcha');
}

b) then creates a verification code using the verification code helper function


$vals = array(
    'word'     => 'Random word',    // Characters displayed on the verification code can be written as functions, such as: rand(100000,999999)
      'img_path'   => './data/captcha/',  // Verification code saving path 
      'img_url'    => base_url('data/captcha'),    // Verification code picture url
      'font_path'   => './path/to/fonts/texb.ttf',    // Font on verification code 
      'img_width'   => '150',    // Verification code picture width 
      'img_height'  => 30,      // Verification code picture height 
      'expiration'  => 7200,     // Verification code picture deletion time 
      'word_length'  => 8,      // Verification code length 
      'font_size'   => 16,      // Verification code font size 
      'img_id'    => 'Imageid',
      'pool'     => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
      'colors'    => array(
              'background' => array(255, 255, 255),
            'border' => array(255, 255, 255),
            'text' => array(0, 0, 0),
            'grid' => array(255, 40, 40)
      ) , 
);

$cap = create_captcha($vals);
var_dump($cap);

In this way, the verification code is created, the parameters img_path and img_url must exist, and the path folder represented by img_path must exist, otherwise the verification code creation will not succeed. Because every time you create a verification code, you will generate a picture and put it in the folder you set, which is very resource-consuming, so we need to optimize the verification code function of CI framework.

2. Optimization of CI framework verification code

Optimization ideas: ① We don't let the pictures generated by the framework be saved to the server; ② We only keep the contents of the verification code.

If we want to optimize the function of verification code, we should expand the auxiliary function of verification code.

a) Extended verification code helper function

First, copy the file "system/helpers/captcha_helper. php" under the root directory to the directory "application/helpers" under the root directory, and name it "MY_captcha_helper. php";

Then comment out the following code (about 96 to 119 lines);


if ($img_path === '' OR $img_url === '' OR ! is_dir($img_path) OR ! is_really_writable($img_path) OR ! extension_loaded('gd'))
{
    return FALSE;
}

// -----------------------------------
// Remove old images
// -----------------------------------

$now = microtime(TRUE);

$current_dir = @opendir($img_path);
while ($filename = @readdir($current_dir))
{
    if (substr($filename, -4) === '.jpg' && (str_replace('.jpg', '', $filename) + $expiration) < $now)
    {
        @unlink($img_path.$filename);
    }
}

@closedir($current_dir);

This code prevents you from pausing function execution without passing img_path and img_url parameters and without the folder the parameters refer to.

Comment the code again (about 318 to 335 lines)


$img_url = rtrim($img_url, '/').'/';

if (function_exists('imagejpeg'))
{
    $img_filename = $now.'.jpg';
    imagejpeg($im, $img_path.$img_filename);
}
elseif (function_exists('imagepng'))
{
    $img_filename = $now.'.png';
    imagepng($im, $img_path.$img_filename);
}
else
{
    return FALSE;
}

$img = '<img '.($img_id === '' ? '' : 'id="'.$img_id.'"').' src="'.$img_url.$img_filename.'" style="width: '.$img_width.'; height: '.$img_height .'; border: 0;" alt=" " />';

This code is used to create a verification code picture and save the picture to the verification code folder you said to create (image_path).

Finally, in create_captcha() Add an header header to the end of the function, and the final code is as follows:


// Direct output 
header("Content-Type:image/jpeg");   // Add a picture format header Head 
imagejpeg($im);
ImageDestroy($im);
// Returns the generated verification code string. If you need other parameters, you can also add the return 
return $word;
//return array('word' => $word, 'time' => $now, 'image' => $img, 'filename' => $img_filename);

b) applies the extended optimized verification code function

Firstly, a method of generating verification code is written in the controller;

Then, the verification code auxiliary function is called in the method to generate the verification code;

Finally, the method is called in the foreground, and the click refresh function is realized.

Generate verification code function code:


// Generate verification code 
public function code()
{
    // Call function to generate verification code , The above parameters can also continue to be used 
    $vals = array(
        'word_length' => 6,
    );
    create_captcha($vals);
}

Foreground call cake real-time refresh call:


<td colspan="2" align="right">
  <img src="<?php echo site_url('admin/privilege/code');?>" alt="" onclick= this.src="<?php echo site_url('admin/privilege/code').'/'?>"+Math.random() style="cursor: pointer;" title=" Can't see clearly? Click Replace Another 1 Verification code. "/>
</td>

At this point, we have completed the optimization of the verification code function mechanism of CI framework.

More readers interested in CodeIgniter can check the topics on this site: "Introduction to codeigniter", "Advanced Course of CI (CodeIgniter) Framework", "Summary of Excellent Development Framework of php", "Introduction to ThinkPHP", "Summary of Common Methods of ThinkPHP", "Introduction to Zend FrameWork Framework", "Introduction to php Object-Oriented Programming", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to PHP programming based on CodeIgniter framework.


Related articles: